<template>
  <el-dialog title="注册账号" :visible="dialogFormVisible" width="50%" @close="closeFn">
    <el-form ref="registerForm" :model="formData" :rules="rules">
      <el-form-item label="用户名" prop="username">
        <el-input v-model.trim="formData.username" autocomplete="off" />
      </el-form-item>
      <el-form-item label="邮箱" prop="email">
        <el-input v-model.trim="formData.email" autocomplete="off" />
      </el-form-item>
      <el-form-item label="密码" prop="password">
        <el-input v-model="formData.password" autocomplete="off" />
      </el-form-item>
    </el-form>
    <div slot="footer" class="dialog-footer">
      <el-button @click="closeFn">取 消</el-button>
      <el-button type="primary" @click="confirmFn">确 定</el-button>
    </div>
  </el-dialog>
</template>

<script>
import { UserRegister } from '@/api/user'
export default {
  props: {
    dialogFormVisible: {
      type: Boolean,
      default: true
    }
  },
  data() {
    return {
      formData: {
        username: '',
        email: '',
        password: ''
      },
      rules: {
        username: [
          { required: true, message: '用户名不能为空', trigger: 'blur' }
        ],
        email: [
          { required: true, message: '邮箱不能为空', trigger: 'blur' },
          {
            pattern: /^\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*$/,
            message: '邮箱格式不对',
            trigger: 'blur'
          }
        ],
        password: [
          { required: true, message: '密码不能为空', trigger: 'blur' }
        ]
      }
    }
  },
  methods: {
    // 取消弹框
    closeFn() {
      this.$emit('update:dialogFormVisible', false)
    },
    // 弹框确认
    async confirmFn() {
      await this.$refs.registerForm.validate()
      try {
        const res = await UserRegister(this.formData)
        this.$message.success('注册成功', res.statusText)
      } catch (error) {
        this.$message.error(error.message)
      }
      this.closeFn()
    }
  }
}
</script>

<style>
</style>
